#include <os_common_api.h>
#include <board.h>
#include <logging/sys_log.h>
#include "csk_6012.h"

struct csk_priv_data {
	struct k_delayed_work work;
	enum csk_work_mode mode;
};

int csk_switch_mode(enum csk_work_mode mode);

static void csk4002_delay_work(struct k_work *work)
{
	struct csk_priv_data *priv = CONTAINER_OF(work, struct csk_priv_data, work);
	SYS_LOG_DBG("swith mode to %d", priv->mode);
	csk_switch_mode(priv->mode);
}

int csk_delay_switch_mode(enum csk_work_mode mode)
{
	static struct csk_priv_data csk4002 = { 0 };
	SYS_LOG_DBG("delay swith mode to %d", mode);
	csk4002.mode = mode;
	os_delayed_work_init(&csk4002.work, csk4002_delay_work);
	return os_delayed_work_submit(&csk4002.work, 0);
}

int csk_switch_mode(enum csk_work_mode mode)
{
	SYS_LOG_INF("==== switch csk to mode: %s ===="
		, ((const char *[]){ "off", "work", "burn", "debug" })[mode]);

	

	switch (mode) {
	case CSK_MODE_DEBUG:
	case CSK_MODE_NORMAL:
		board_csk_load(1);
		break;
	case CSK_MODE_BURN:
	case CSK_MODE_PWROFF:
		board_csk_load(0);
		break;
	default:
		break;
	}

	switch (mode) {
	case CSK_MODE_NORMAL:
	case CSK_MODE_DEBUG:
	case CSK_MODE_BURN:
		board_csk_sys_rst(0);
		break;
	case CSK_MODE_PWROFF:
		board_csk_sys_rst(0);
		break;
	default:
		break;
	}
	
	
	switch (mode) {
	case CSK_MODE_NORMAL:
	case CSK_MODE_DEBUG:
		k_sleep(200);
		board_csk_sys_rst(1);
		break;
	case CSK_MODE_BURN:
		k_sleep(200);
		board_csk_sys_rst(1);
		break;
	case CSK_MODE_PWROFF:
	default:
		break;
	}
	k_sleep(50);
	switch (mode) {
	case CSK_MODE_PWROFF:
	case CSK_MODE_NORMAL:
		break;
	case CSK_MODE_BURN:
		board_usb_select(2);
		break;
	case CSK_MODE_DEBUG:
		board_usb_select(1);
		break;
	default:
		break;
	}
	SYS_LOG_INF("csk mode switch done!");
	return 0;
}



